package com.fatdetection.demo.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtils {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${tokenExpTime}")
    private Integer EXP;
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    /**
     * token 生成
     */
    public String geneToken(Map<String, String> params){
        long outDateTime = System.currentTimeMillis() + EXP * 1000;
        Date date = new Date(outDateTime);
        String token = Jwts.builder()
                .setIssuer("xiaoRan")
                .setClaims(params)
                .setExpiration(date)
                .signWith(SECRET_KEY)
                .compact();
        stringRedisTemplate.opsForValue().set(token, String.valueOf(date.getTime()), EXP, TimeUnit.SECONDS);
        // 存入 redis
        return token;
    }

    /**
     * token 检验是否过期
     */
    public Claims verifyToken(String token)
            throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException{
            return Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token).getBody();
    }
}
